import React, { Component } from "react";

class SetState extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
    };
  }
  componentDidMount() {
    document.getElementById("test").addEventListener("click", this.setCounter);
  }
  // changeValue = (v) => {
  //   this.setState(
  //     {
  //       counter: this.state.counter + v,
  //     },
  //     () => {
  //       console.log("counter", this.state.counter);
  //     }
  //   );
  //   // console.log("counter", this.state.counter);
  // };
  changeValue = (v) => {
    this.setState((state) => ({ counter: state.counter + v }));
  };
  // setCounter = () => {
  //   setTimeout(() => {
  //     this.changeValue(1);
  //   }, 0);
  // };
  setCounter = () => {
    this.changeValue(1);
    // 后面会覆盖前面
    this.changeValue(2);
    this.changeValue(3);
  };

  render() {
    return (
      <div>
        <h3>SetState</h3>
        <button onClick={this.setCounter}>{this.state.counter}</button>
        <button id="test">
          原生事件:
          {this.state.counter}
        </button>
      </div>
    );
  }
}

export default SetState;
